#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <stdbool.h>

void Print(int* a, int n)
{
	for (int i = 0;i < n; i++)
	{
		printf("%d ", a[i]);
	}
	printf("\n");
}

void Swap(int* a, int* b)
{
	int tmp = *a;
	*a = *b;
	*b = tmp;
}

void AdjustUp(int* arr, int child)
{
	int parents = (child - 1) / 2;
	while (child > 0)
	{
		if (arr[child] < arr[parents])
		{
			Swap(&arr[child], &arr[parents]);
			child = parents;
			parents = (child - 1) / 2;
		}
		else
		{
			break;
		}
	}
}

void AdjustDown(int* arr, int n, int parents)
{
	//假设法：假设左孩子小
	int child = (parents * 2) + 1;
	//建小堆：谁小谁上去
	while (child < n)	//	child >= n 的时候说明超过了数组长度本身
	{
		if ((child + 1) < n && arr[child + 1] < arr[child])
		{
			child++;
		}
		if (arr[child] < arr[parents])
		{
			Swap(&(arr[child]), &(arr[parents]));
			parents = child;
			child = (parents * 2) + 1;
		}
		else
		{
			break;
		}
	}
}

//降序：建小堆（升序：建大堆）
void HeapSort(int* a, int n)
{
	//向上调整算法建堆：复杂度O(NlogN)
	//for (int i = 1;i < n;i++)
	//{
	//	AdjustUp(a, i);
	//}
	//向下算法建堆：复杂度O(N)
	for (int i = (n - 1 - 1) / 2;i >= 0;i--)
	{
		AdjustDown(a, n, i);
	}
	int end = n - 1;
	while (end > 0)
	{
		Swap(&a[0], &a[end]);
		AdjustDown(a, end, 0);
		end--;
	}
}

int main()
{
	int arr[] = { 5,2,3,9,8,7,4,6,1};
	Print(arr, sizeof(arr) / sizeof(arr[0]));
	HeapSort(arr, sizeof(arr) / sizeof(arr[0]));
	Print(arr, sizeof(arr) / sizeof(arr[0]));
	return 0;
}